 package com.example.weight.wormHandle.cultivate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.MyAdapter;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.waterDeal.EquipmentDailyMaintainTable;
import com.example.weight.util.WeightActivity;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.BatchGroupNumber;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class HatchingOutcoming extends AppCompatActivity {
    private String name, selectBatchText, factory;
    private  int belongTo_id = -1;

    private Spinner batchGroupNumber;
    private EditText end_time;
    private EditText after_weight;
    private String is_terminate_cultivation = "",remarks = "";
    private RadioGroup radioGroup;
    RadioButton btn_yes, btn_no;


    private List<BatchGroupNumber> batchGroupNumberList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hatching_outcoming);
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                HatchingOutcoming.this.finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });
        radioGroup = (RadioGroup)findViewById(R.id.peiyu_group_button);
        btn_yes = (RadioButton)findViewById(R.id.shi_button);
        btn_no = (RadioButton)findViewById(R.id.fou_button);
        btn_yes.setOnClickListener(v -> {
            if (btn_yes.isChecked()) {
                setTerminateCultivation();
            }
        });
        btn_no.setOnClickListener(v -> {
            if (btn_no.isChecked()) {
                setContinueCultivation();
            }
        });

         batchGroupNumber = findViewById(R.id.sp_primary_key);
         end_time=findViewById(R.id.et_end_time);
         after_weight=findViewById(R.id.et_box_weight);
         batchGroupNumberList = new ArrayList<>();

        //获取1-3待填写的批次、组别、孵化盒号列表
            RequestQueue queue = Volley.newRequestQueue(this);
            String url2 = Config.url + "/hsmpy/HatchedMaterial/getlist" + "?factory=" + factory;
            StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (!jsonObject.isNull("data")) {
                                    JSONArray data = jsonObject.getJSONArray("data");
                                    Log.d("jy", data.toString());
                                    if( data.length()>0){
                                        for (int i=0; i < data.length(); i++){
                                            JSONObject record = data.getJSONObject(i);
                                            batchGroupNumberList.add(new BatchGroupNumber(record.getInt("id"),record.getString("batch"),record.getString("wormGroup"),record.getString("hatchBoxNumber"),"",record.getString("date")));
                                        }
                                        Log.d("jy", batchGroupNumberList.toString());
                                        ArrayAdapter<BatchGroupNumber> adapter = new ArrayAdapter<BatchGroupNumber>(HatchingOutcoming.this, android.R.layout.simple_spinner_item,batchGroupNumberList);
                                        batchGroupNumber.setAdapter(adapter);
                                        batchGroupNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                            @Override
                                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                                belongTo_id = batchGroupNumberList.get(position).id;
                                                end_time.setText(batchGroupNumberList.get(position).date);//设置时间修改
                                            }

                                            @Override
                                            public void onNothingSelected(AdapterView<?> parent) {
                                                belongTo_id = -1;
                                            }
                                        });
                                        batchGroupNumber.setSelection(0,true);
                                    }else {
                                        Toast.makeText(HatchingOutcoming.this, "没有可操作的数据", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(HatchingOutcoming.this,
                            "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
            stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(stringRequest2);
        }

        @SuppressLint("ResourceType")
        public void chooseEndDate(View view) {
            Calendar calendar=Calendar.getInstance();
            new DatePickerDialog(HatchingOutcoming.this,2,
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year,
                                              int month, int day) {
                            // TODO Auto-generated method stub
                            Integer mYear = year;
                            Integer mMonth = month;
                            Integer mDay = day;
                            end_time.setText(new StringBuilder()
                                    .append(mYear)
                                    .append("-")
                                    .append((mMonth + 1) < 10 ? "0"
                                            + (mMonth + 1) : (mMonth + 1))
                                    .append("-")
                                    .append((mDay < 10) ? "0" + mDay : mDay));
                        }
                    }
                    // 设置初始日期
                    , calendar.get(Calendar.YEAR)
                    , calendar.get(Calendar.MONTH)
                    , calendar.get(Calendar.DAY_OF_MONTH)).show();
        }

        public void submit(View view) {
            if (belongTo_id == -1) {
                Toast.makeText(this, "请选择批次、组别、孵化盒号", Toast.LENGTH_SHORT).show();
                return;
            }
            if(end_time.getText().toString().equals("")) {
                Toast.makeText(this, "请填写孵化结束日期", Toast.LENGTH_SHORT).show();
                return;
            }
//            if (after_weight.getText().toString().equals("")) {
//                Toast.makeText(this, "请填写孵化后盒+料总重量", Toast.LENGTH_SHORT).show();
//                return;
//            }
            if (is_terminate_cultivation.equals("")) {
                Toast.makeText(this, "请选择是否终止培育", Toast.LENGTH_SHORT).show();
                return;
            }

            new AlertDialog.Builder(this)
                    .setTitle("确定保存吗？")
                    .setCancelable(false)
                    .setNegativeButton("取消", ((dialog, which) ->
                            Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                    .setPositiveButton("确定", (dialog, which) -> {

                        //提交请求
                        RequestQueue queue = Volley.newRequestQueue(this);
                        String url = Config.url + "/hsmpy/HatchedMaterial/add";
                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                        Log.d("LB", response);
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            String code = jsonObject.getString("code");
                                            if (code.startsWith("2"))
                                                Toast.makeText(HatchingOutcoming.this,
                                                        "保存成功", Toast.LENGTH_SHORT).show();
                                            else
                                                Toast.makeText(HatchingOutcoming.this,
                                                        "保存失败", Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(HatchingOutcoming.this, "保存失败", Toast.LENGTH_SHORT).show();
                                Log.d("jy", error.toString());
                            }
                        }) {
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                Map<String, String> map=new HashMap<>();
                                map.put("id", belongTo_id+"");
                                map.put("hatch_end_time", end_time.getText().toString());
//                                map.put("fhhlkfhw_weight", after_weight.getText().toString());
                                map.put("is_stop", is_terminate_cultivation);
                                map.put("remark", remarks);
                                map.put("factory", factory);
                                if (after_weight.getText().toString().equals("")) {
                                    map.put("fhhlkfhw_weight", "0");
                                }else {
                                    map.put("fhhlkfhw_weight", after_weight.getText().toString());
                                }
                                return map;
                            }
                        };
                        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                        queue.add(stringRequest);
                    })
                    .show();
        }
        public void setContinueCultivation() {
            new androidx.appcompat.app.AlertDialog.Builder(this)
                    .setTitle("确定继续培育？")
                    .setCancelable(false)
                    .setNegativeButton("取消", ((dialog, which) ->{
                        radioGroup.clearCheck();
//                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    }))
                    .setPositiveButton("确定", (dialog, which) ->{
                        // 提交表单
                        is_terminate_cultivation="否";
                    })
                    .show();
        }

        public void setTerminateCultivation() {
            final EditText equipment_problem = new EditText(this);
            equipment_problem.setHint("   输入原因:");
            new androidx.appcompat.app.AlertDialog.Builder(this)
                    .setTitle("请填写终止培育的原因")
                    .setView(equipment_problem)
                    .setCancelable(false)
                    .setNegativeButton("取消", ((dialog, which) ->{
                        radioGroup.clearCheck();
//                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    }
                    ))
                    .setPositiveButton("确定", (dialog, which) ->{
                        remarks=equipment_problem.getText().toString();
                        is_terminate_cultivation="是";
                    })
                    .show();
        }
}